package com.example.base_kotlin_xml.view

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base_kotlin_xml.R
import com.example.base_kotlin_xml.adapter.RoomAdapter
import com.example.base_kotlin_xml.databinding.FragmentRoomBinding
import com.example.base_kotlin_xml.model.RoomViewModel
import com.example.base_model.ext.castTo
import com.example.base_model.ext.castToListOf
import com.example.base_model.ext.castToMap
import com.example.base_model.ext.whenStatus
import com.example.base_model.network.load.LoadingStrategy
import com.example.base_model.network.request_param.RequestParamInterface
import com.example.base_model.room.bean.User
import com.example.base_model.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map

/**
 * @Author: jiangKunKun
 * @CreateDate: 2025/7/31
 * @Description: room数据库
 * @SpittingGrooves
 */
@AndroidEntryPoint
class RoomFragment : BaseFragment<FragmentRoomBinding>() {
    val vModel: RoomViewModel by viewModels()
    var userList = mutableListOf<User>()
    val adapter = RoomAdapter()
    override fun initObservers() {
        launchAndCollect {
            vModel.uiState
                .map { it.isLoading(LoadingStrategy.MAIN) } // 使用枚举检查状态
                .distinctUntilChanged()
                .collectLatest { isLoading ->
                    if (isLoading) {
                        showLoading("加载中...")
                    } else {
                        LogUtils.d("isLoading 关闭")
                        hideLoading()
                    }
                }
        }
        launchAndCollect{
            // room添加
            vModel.uiState.map { it.addUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room添加 开始状态")
                        },
                        dataSuccess = {
                            roonParamCallBack(it.requestParam)
                            LogUtils.d("room添加 成功状态", it.requestParam)
                        },
                        error = {
                            LogUtils.d("room添加 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room添加 结束状态")
                        }
                    )
                }
        }
        launchAndCollect{
            // room更改
            vModel.uiState.map { it.updateUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room更改 开始状态")
                        },
                        dataSuccess = {
                            roonParamCallBack(it.requestParam)
                            LogUtils.d("room更改 成功状态", it.data, it.requestParam)
                        },
                        error = {
                            LogUtils.d("room更改 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room更改 结束状态")
                        }
                    )
                }
        }

        launchAndCollect{
            // room删除一个
            vModel.uiState.map { it.deleteUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room删除 开始状态")
                        },
                        dataSuccess = {
                            roonParamCallBack(it.requestParam)
                            LogUtils.d("room删除 成功状态", it.data, it.requestParam)
                        },
                        error = {
                            LogUtils.d("room删除 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room删除 结束状态")
                        }
                    )
                }
        }

        launchAndCollect{
            // room查询一个
            vModel.uiState.map { it.selectUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room查询 开始状态")
                        },
                        dataSuccess = {
                            roonParamCallBack(it.requestParam)
                            it.data?.let { it ->
                                LogUtils.d("room查询 获取结果: ", it.id, it.name, it.email)
                            }
                            LogUtils.d("room查询 成功状态", it.data, it.requestParam)
                        },
                        error = {
                            LogUtils.d("room查询 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room查询 结束状态")
                        }
                    )
                }
        }

        launchAndCollect{
            // room查询全部
            vModel.uiState.map { it.selectAllUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room查询全部 开始状态")
                        },
                        dataSuccess = {
                            it.data?.forEach { it ->
                                LogUtils.d("room查询全部 获取结果: ", it.name, it.email)
                            }
                            LogUtils.d("room查询全部 成功状态", it.data)
                        },
                        error = {
                            LogUtils.d("room查询全部 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room查询全部 结束状态")
                        }
                    )
                }
        }

        launchAndCollect{
            // room删除全部
            vModel.uiState.map { it.deleteAllUserResult }
                .distinctUntilChanged()
                .collectLatest {
                    it.status.whenStatus (
                        start = {
                            LogUtils.d("room删除全部 开始状态")
                        },
                        dataSuccess = {
                            LogUtils.d("room删除全部 成功状态", it.data)
                        },
                        error = {
                            LogUtils.d("room删除全部 错误状态", it.code, it.msg)
                        },
                        finish = {
                            LogUtils.d("room删除全部 结束状态")
                        }
                    )
                }
        }

        launchAndCollect {
            vModel.allUsersStateFlow.collectLatest {
                LogUtils.d("实时监听room", it.toString())
                userList.clear()
                userList.addAll(it)
                adapter.submitList(userList)
            }
        }
    }
    private fun roonParamCallBack(param: RequestParamInterface?) {
        if (param is RequestParamInterface) {
            // 处理 List<Bean>
            param.castToListOf<User> { list ->
                list.forEach { it ->
                    LogUtils.d("castToListOf 成功: ${it.name}, ${it.email}")
                }
            }

            // 处理 Map
            param.castToMap { map ->
                LogUtils.d("原始 Map 参数: $map")
            }

            // 处理单个 Bean
            param.castTo<User> { bean ->
                LogUtils.d("castTo 成功: ${bean.name}, ${bean.email}")
            }
        }
    }

    override fun initClickEvents() {
        // 添加用户
        mBinding.btnRoomAdd.setOnClickListener {
            val name: String? = mBinding.editRoomAddName.text.toString().trim()
            name?.let {
                val email = mBinding.editRoomAddEmail.text.toString()
                vModel.addUser(name, email)
            } ?: run {
                ToastUtils.showShort("请输入用户名")
            }
        }
        // 修改用户
        mBinding.btnRoomUpData.setOnClickListener {
            // 判断更改的id 和用户名称不能为空
            val userId = mBinding.editRoomUpDataId.text.toString().toIntOrNull()
            val name = mBinding.editRoomUpDataName.text.toString()
            if (userId == null) {
                ToastUtils.showShort("用户id不能为空")
                return@setOnClickListener
            }
            if (name.isEmpty()) {
                ToastUtils.showShort("姓名不能为空")
                return@setOnClickListener
            }
            vModel.updateUser(User(userId, name, mBinding.editRoomUpDataEmail.text.toString().trim()))
        }
        // 删除单个
        mBinding.btnRoomDelete.setOnClickListener {
            val userId = mBinding.editRoomDeleteId.text.toString().toIntOrNull()
            if (userId == null) {
                ToastUtils.showShort("用户ID不能为空")
                return@setOnClickListener
            }
            vModel.deleteUser(userId)
        }
        // 查询单个
        mBinding.btnRoomQuery.setOnClickListener {
            val userId = mBinding.editRoomQueryId.text.toString().toIntOrNull()
            if (userId == null) {
                ToastUtils.showShort("用户ID不能为空")
                return@setOnClickListener
            }
            vModel.getUserById(userId)
        }
        // 查询全部
        mBinding.btnRoomQueryAll.setOnClickListener {
            vModel.getUserAll()
        }
        // 删除全部
        mBinding.btnRoomDeleteAll.setOnClickListener {
            vModel.deleteAllUsers()
        }

    }

    override fun initData() {
        mBinding.rvRoomList.layoutManager = LinearLayoutManager(activity)
        adapter.submitList(userList)
        mBinding.rvRoomList.adapter = adapter
    }

    override fun attachLayoutRes(): Int = R.layout.fragment_room
}